package edu.nwmissouri.galaxygames;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;



import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


public class AnnouncementFragment extends Fragment{

	//array list to store annoucements
	public static ArrayList<Announcement> announcementList = new ArrayList();
	
	//text view to display events
	TextView annoucementDisplay;
	LinearLayout annoucementLinearLayout;
	
	//stores whether or not the annoucncement have already been downloaded
	public static boolean annoucementsCached = false;
	
	//the constant value use to offset the id of each announcement
	final int ID_OFFSET = 1000;
	
	@Override
	public void onCreate(Bundle bundle){
		super.onCreate(bundle);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup view, Bundle bundle)
	{
	    return inflater.inflate(R.layout.activity_announcement, view, false);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}
	
	@Override
	public void onStart(){
		
		super.onStart();
		
		//set annoucementDisplay to textview in xml
		annoucementLinearLayout = (LinearLayout)getActivity().findViewById(R.id.announcementLinearDisplay);
		
		//find and set up the on click listener for the refresh button
		Button refreshButton = (Button)getActivity().findViewById(R.id.announcementRefreshButton);
		
		refreshButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				
				//call method to refresh announcement list
				refreshAnnouncementList();
				
			}
		});
		
		if(!annoucementsCached){
			
			//attempt to download the file from the internet
			if(isNetworkAvailable()){
				
				//Create network dialog
				((MainActivity)getActivity()).makeEventLoadDialog();
				
				//reads the events calendar file from the internet
				readAnnoucements();
			}
			else{
				//if a connection is not available, notify the user and return to the main menu
				((MainActivity)getActivity()).makeNetworkErrorDialog();
			}
			
		}
		else if(annoucementsCached){
			populateAnnoucementList();
		}
		
	}
		
		//refresh the event list
		public void refreshAnnouncementList(){
			
			if(isNetworkAvailable()){
				
				//clear the event array list
				announcementList = new ArrayList();
				
				//clear the event list
				annoucementLinearLayout.removeAllViews();
				
				//Create network dialog
				((MainActivity)getActivity()).makeEventLoadDialog();
				
				//reads the events calendar file from the internet
				readAnnoucements();
			}
			else{
				//if a connection is not available, notify the user and return to the main menu
				((MainActivity)getActivity()).makeNetworkErrorDialog();
			}
		}
		
		//returns true if the device has a connection to the internet
		public boolean isNetworkAvailable() {
			ConnectivityManager cm = (ConnectivityManager) 
				      getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
				    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
				    // if no network is available networkInfo will be null
				    // otherwise check if we are connected
				    if (networkInfo != null && networkInfo.isConnected()) {
				        return true;
				    }
				    return false;
		}
		
		//reads the event calendar from the server
		public void readAnnoucements(){
			DownloadAnnoucementsTask task = new DownloadAnnoucementsTask(((MainActivity)getActivity()));
		    task.execute(new String[] { "https://dl.dropboxusercontent.com/u/59131634/announcements.txt" });
		}
		
		//recieves lines of text, places the text appropriately into an events and adds the events
		//to the event list.  Once completed, it caches the events and tells the list to be populated.
		public void createAnnoucements(String line){
			
			//split the string into an array by lines
			String [] lineArray = line.split(";");
			
			for(int i = 0; i<lineArray.length; i++){
				//split line into parts
				String[] currentLineParts = lineArray[i].split("#");
				
				//create announcement
				Announcement announcementToAdd = new Announcement(currentLineParts[0], currentLineParts[1]);
				
				//add to list
				announcementList.add(announcementToAdd);
				
			}
			
			//the annoucements are not cached
			annoucementsCached = true;
			
			//populate the list
			populateAnnoucementList();
			
		}
		
		//populates the text view with all currently loaded events
		public void populateAnnoucementList(){
			
			
			
			//text view to add to scroll view
			TextView textViewToAdd;
			
			//border to separate event text views
			View border;
			
			for(int i = 0; i<announcementList.size(); i++){
				
				//set text view params and id
				textViewToAdd = new TextView(getActivity().getBaseContext());
				textViewToAdd.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
				
				textViewToAdd.setId(i + ID_OFFSET);
				textViewToAdd.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View textViewClicked) {
							//retrieve the current event to show from the event list
							Announcement annoucementToShow = announcementList.get(textViewClicked.getId() - 1000);
							((MainActivity)getActivity()).makeAnnoucementDialog(annoucementToShow);
							
							
						}
					});
				
				Announcement currentAnnouncement = announcementList.get(i);
				
				//set text to current announcements title
				textViewToAdd.setText("\n" + currentAnnouncement.getTitle() + "\n");
				textViewToAdd.setTextColor(Color.BLACK);
				
				//add textView to linear layout inside scroll view
				annoucementLinearLayout.addView(textViewToAdd);
				
				//add a border
				border = new View(getActivity().getBaseContext());
				border.setLayoutParams(new LinearLayout.LayoutParams(800, 1));
				border.setBackgroundColor(android.graphics.Color.BLACK);
				annoucementLinearLayout.addView(border);
				
				
				
			}
			
			
			
			
			
			
			
			
		}
		
		private class DownloadAnnoucementsTask extends AsyncTask<String, Void, String> {
		    
		    private WeakReference<MainActivity> parent;
		    
		    public DownloadAnnoucementsTask (MainActivity parentActivity)
		    {
			this.parent = new WeakReference<MainActivity>(parentActivity);
		    }
			 
		    @Override
		    protected String doInBackground(String... urls) {
		      String response = "";
		      for (String url : urls) {
		        DefaultHttpClient client = new DefaultHttpClient();
		        HttpGet httpGet = new HttpGet(url);
		        try {
		          HttpResponse execute = client.execute(httpGet);
		          InputStream content = execute.getEntity().getContent();

		          BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
		          String s = "";
		          while ((s = buffer.readLine()) != null) {
		            response += s;
		          }

		        } catch (Exception e) {
		        	
		        }
		      }
		      return response;
		    }

		    @Override
		    protected void onPostExecute(String result) {
		    
		    	//close the alert dialog
		    	MainActivity parentActivity = parent.get();
		    	parentActivity.dismissNetworkDialog();
		    	createAnnoucements(result);
		    }
		  }
		
	
	
}


